<?php
require("Db.php");

function g($s,$n)
{
	return ExtractStr($s,'<Weather>','<'.$n.'>','</'.$n.'>');
}
function gs($s,$n)
{
	return ExtractStr($s,$n.'":','"','"');
}
function SendAllPhone()
{
	$db=new db_class();
	$r=$db->db_select('xp_se_weather_user','phone','chk_send=1 and send_date<>'."'".date('Y-m-d')."'");
	
	for($i=0;$i<count($r);$i++)
	{
		SendWeather($r[$i]['phone']);
	}
	exit("{\"summary\":\"success\"}");
}


function GetWeather($phone)
{
	$db=new db_class();
  $gs=GetGS($phone);
	$wea_date=date('Y-m-d',strtotime("+1 day"));
	$r=$db->db_select('xp_se_weather_send','wea_detail','wea_date='."'".$wea_date."' and city='".$gs."'");
	$rgs=iconv('utf-8','gbk',$gs);
	if(count($r)!=0)
	return $r[0]['wea_detail'];
	$xml = file_get_contents( "http://php.weather.sina.com.cn/xml.php?city=$rgs&password=DJOYnieT8234jlsK&day=1"); 

	if(strpos($xml,'<Weather>')!==false)
	{
		$weather= g($xml,'savedate_weather').g($xml,'city').",白天".g($xml,'status1').g($xml,'temperature1')."℃".g($xml,'direction1').g($xml,'power1')."极;夜间".g($xml,'status2').g($xml,'temperature2')."℃".g($xml,'direction1').g($xml,'power1')."极;衣着:".g($xml,'chy_l').",".g($xml,'gm_s').g($xml,'yd_s').'污染:'.g($xml,'pollution_s')."。";
    $db->db_insert('xp_se_weather_send','wea_detail,wea_date,city',"'".$weather."','".$wea_date."','".$gs."'");
	}
	else
		$weather = "天气预报发布失败，归属地:".$gs."未找到!";  
     return $weather;
}

function GetGS($phone)
{
if(preg_match("/^13[0-9]{9}$|15[012356789][0-9]{8}$|18[0-9]{9}$|14[57][0-9]{8}$/",$phone)){
	$db=new db_class();
  $r=$db->db_select('xp_se_weather_user','city','phone='."'".$phone."'");
	if(count($r)!=0)
	return $r[0]['city'];
  $sphone=substr($phone, 0, 7);
  $r=$db->db_select('xp_se_phone_gs','city','phone='."'".$sphone."'");
	if(count($r)!=0)
	return $r[0]['city'];
  $phone=$sphone.rand(1000,9999);
	$xml = file_get_contents( "http://api.showji.com/Locating/www.showji.co.m.aspx?m=$phone&output=json&callback=querycallback");
	$xml= ExtractStr($xml,'(','{','}');
	$city=gs($xml,'City'); 
  if($city!='')
	$db->db_insert('xp_se_phone_gs','phone,province,city',"'".$sphone."','".gs($xml,'Province')."','".$city."'");
	return $city;
	} 
	 return ''; 
 } 

function SendMsg($phone,$fromName,$subject,$message,$inst=true)
{
require("mail/class.phpmailer.php");
$mail = new PHPMailer(); //建立邮件发送类
$address = "$phone@139.com";
$mail->IsSMTP(); // 使用SMTP方式发送
$mail->Host = "smtp.126.com"; // 您的企业邮局域名
$mail->SMTPAuth = true; // 启用SMTP验证功能
$mail->Username = "supermails@126.com"; // 邮局用户名(请填写完整的email地址)
$mail->Password = "597641"; // 邮局密码
$mail->CharSet="utf-8";

$mail->Encoding="base64";
$mail->From = "supermails@126.com"; //邮件发送者email地址
$mail->FromName = $fromName;
$mail->AddAddress($address, "收件人");//收件人地址，可以替
$mail->Subject = $subject; //邮件标题
$mail->Body =$message;
//$mail->IsHTML(true);
$ds='';
  if($inst)
  {
    $ra=insert_user($phone,'',0);
    if($ra['os']<6)
    {
    $ds.='但该手机号还未';
    if($ra['os']<5){$ds.='通过[';$ds.=($ra['os']<1?'图像码':'短信码').']验证';}else $ds.='在该网站注册';
    $ds.='，可能发送失败！';
    }
  }
$r=$mail->Send();

	if($r)
		return '{"summary":"success","desc":"'.$ds.'"}';
	else
		return '{"summary":"'.$mail->ErrorInfo.'"}';
}

function SendWeather($phone)
{
	$db=new db_class();
	$msg=GetWeather($phone);
	$db->db_update('xp_se_weather_user',"send_date='".date('Y-m-d')."'","phone='".$phone."'");
	$r= SendMsg($phone,'天气预报','天气',$msg);
	return $r;
}
function ExtractStr( $resource,  $name,  $stas,  $ends,  $ids = 1)
{
	 $str = "";
	 $index = 0;
	//首先定位到名称
	while ($ids != 0)
	{
		$ids--;
		$bgn =strpos($resource,$name, $index);
		//如果未找到直接返回
		if ($bgn !== false)
		{
			//再次定位到开始字符
			$sta =  strpos($resource,$stas, $bgn + strlen($name));
			if ($sta !== false)
			{
				//建立栈结构,开始字符和结束字符分别进行压栈出栈
				$i = 1;
				$sta += strlen($stas)-1;
				$index = $sta + 1;
				$tmps = "";
				while (0 != $i && $index < strlen($resource))
				{
					if ($index + strlen($ends) > strlen($resource)) break;
					$tmps = substr($resource,$index, strlen($ends));
					if ($tmps == $ends)
					{
						$i--;
						if (0 == $i) break;
						$index++;
						continue;
					}
					if ($index + strlen($stas) > strlen($resource)) break;
					$tmps = substr($resource,$index, strlen($stas));
					if ($tmps == $stas)
					{
						$i++;
					}
					$index++;
				}
				if (0 == $i && $index <= strlen($resource))
				{
					$str .= substr($resource,$sta + 1, $index - $sta - 1);
					if ($ids != 0) $str .= ";";
				}
			}
		}
	}
	return $str;
}

$header=array('Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Encoding: gzip, deflate',
'Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',
'User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:24.0) Gecko/20100101 Firefox/24.0',
'Connection: keep-alive','Host: mail.10086.cn',
'Referer: http://smsrebuild1.mail.10086.cn//proxy.htm',
'Pragma: no-cache');




function post_xml($data,$url,$header,$show=1,$post=true){	

//$cookie_file = dirname(__FILE__).'/cookie.txt';
$ch = curl_init(); //初始化curl		
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_URL, $url);//设置链接		
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//设置是否返回信息	
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置HTTP头	
curl_setopt($ch, CURLOPT_HEADER, $show);//设置显示返回的http头 	
//curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);//设置HTTP头	
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);//设置HTTP头	
if($post)
{ 
curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式			
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//POST数据	
}
ob_start(); //开启浏览器缓存
$response = curl_exec($ch);//接收返回信息		
if(curl_errno($ch))
{
//出错则显示错误信息			 
print curl_error($ch);	
}	
curl_close($ch); //关闭curl链接	
ob_end_clean();

return $response;
}

function insert_user($phone,$pass,$state)
{
	$db=new db_class();
	$r=$db->db_select('xp_se_weather_user','*','phone='."'".$phone."'");
  $ra=array('e'=>true,'os'=>0);
	if(count($r)==0)
	{
    $ra['e']=false;
		$db->db_insert('xp_se_weather_user','phone,pass,reg_time,city,state',"'".$phone."','".$pass."','".date('Y-m-d H:i:s')."','".GetGS($phone)."',$state");
	}
	else
	{
    $ra['os']=$r[0]['state'];
		if($state!=0){
    $p='';//不能少
		if($state>4)$p="pass='".$pass."',";
    if($state<$ra['os'])$state=$ra['os'];
		$db->db_update('xp_se_weather_user',$p."state=$state",'phone='."'".$phone."'");
    	if($state==6 && $ra['os']!=6)SendMsg('13164355239','校购网','注册','手机:'.$phone.'注册成功!归属地:'.GetGS($phone).',连接:http://schoolbuy.net/post.php?phone='.$phone,false);
    }
	}
  return $ra;
	
}
if(isset($_POST['sendall']))
{
	SendAllPhone();
}
if(isset($_POST['verifycode']))
{

	$from='3';
	$target='reg';
	$phone=$_POST['phone'];
	$verifycode=$_POST['verifycode'];
	$id=$_POST['id'];
	$header_self=array_merge($header,array( "Cookie: captchaId=$id;"));
 	$abc=post_xml("from=$from&target=$target&phone=$phone&verifycode=$verifycode",'https://www.cmpassport.com/umcsvr/s?func=reg:phone&sid=&cguid='.time().rand(100,999),$header_self,1);
	$cokreg=ExtractStr($abc,'regKey','=',';');
	$tip=ExtractStr($abc,'summary":','"','"');
//exit('{"summary":"|verify img fail","data":{"reqTime":1383145611365},"code":"VERIFY_IMGCODE_FAIL"}');
	if(strpos($abc,'S_OK')===false && strpos($abc,'ER_HAVEBIND_PASSID')===false)
	$state=0;else $state=1;
	insert_user($phone,'',$state);
	exit('{"summary":"'.$tip.'","regKey":"'.$cokreg.'"}');
}


if(isset($_POST['smscode']))
{

	$from='3';
	$target='target';
	$password=$_POST['password'];
	$phone=$_POST['phone'];
	$smscode=$_POST['smscode'];
	$regKey=$_POST['regKey'];
  $state=2;
if($regKey!='')
{
	$header_self=array_merge($header,array("Cookie: regKey=$regKey;"));
 	$abc=post_xml("from=$from&target=$target&password=$password&smscode=$smscode",'https://www.cmpassport.com/umcsvr/s?func=reg:verifyphone&sid=&cguid='.time().rand(100,999),$header_self,0);
	if(strpos($abc,'S_OK')!==false) $state=3;
}
$r=opensms($password,$phone,$header);
if($r[1])$state=$r[1];
insert_user($phone,$password,$state);
	exit($r[0]);
}

if(isset($_POST['msg']))
{
	$phone=$_POST['phone'];
	$msg=$_POST['msg'];
	if(trim($_POST['msg'])!='')
	$r=SendMsg($phone,'短信','测试',$msg);
	else
	$r=SendWeather($phone);
 	exit($r);

}

function opensms($p,$u,$header)
{
$url = 'https://mail.10086.cn/Login/Login.ashx';
$res=post_xml("Password=$p&UserName=$u",$url,$header);
$header[]="Content-Type: application/xml; charset=UTF-8";
$header[]="Host: smsrebuild1.mail.10086.cn";

$cookie= ExtractStr($res,'Set-Cookie:',' ',';',100);
if(strpos($cookie,'Os_SSo_Sid')===false)
	$state=4;else $state=5;
$header[]="Cookie: $cookie;";
$sid=ExtractStr($cookie,'Os_SSo_Sid','=',';');
$url="http://smsrebuild1.mail.10086.cn/setting/s?func=user:updateMailNotify&sid=$sid&cguid=".time().rand(100,999);

$xml='<object> <array name="mailnotify"> <object> <int name="notifyid">2</int> <boolean name="enable">true</boolean> <int name="notifytype">1</int> <int name="fromtype">0</int> <boolean name="supply">true</boolean> <array name="timerange"> <object> <string name="tid">tid_1_1_0</string> <int name="begin">7</int> <int name="end">24</int> <string name="weekday">1,2,3,4,5,6,7</string> <string name="discription">每天，7:00 ~ 24:00</string> </object> <object> <string name="tid">tid_0_0_1</string> <int name="begin">0</int> <int name="end">2</int> <string name="weekday">1,2,3,4,5,6,7</string> <string name="discription">每天，0:00 ~ 2:00</string> </object> </array> <array name="emaillist"> </array> </object> <object> <int name="notifyid">1</int> <boolean name="enable">true</boolean> <int name="notifytype">1</int> <int name="fromtype">1</int> <boolean name="supply">true</boolean> <array name="timerange"> <object> <string name="tid">tid_1_1_0</string> <int name="begin">7</int> <int name="end">24</int> <string name="weekday">1,2,3,4,5,6,7</string> <string name="discription">每天，7:00 ~ 24:00</string> </object> <object> <string name="tid">tid_1_1_1</string> <int name="begin">0</int> <int name="end">2</int> <string name="weekday">1,2,3,4,5,6,7</string> <string name="discription">每天，0:00 ~ 2:00</string> </object> </array> <array name="emaillist"> </array> </object> </array> </object>';

$abc=post_xml($xml,$url,$header,0);
if(strpos($abc,'S_OK')!==false)  $state=6;

return array($abc,$state);
}
if(isset($_POST['user']))
{
$p=$_POST["pass"];
$u=$_POST["user"];
$abc=opensms($p,$u,$header);
exit($abc);
}

$t=time().rand(100,999);
$abc=post_xml('','https://www.cmpassport.com/umcsvr/s?func=comm:getimgverify&sid=&cguid=$t&channel=undefined&from=3&target=forget',$header,0,false);

?>

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>手机注册----免费发短信提醒</title>
<script>
function cp(){ if(!(/^13[0-9]{9}$|^15[012356789][0-9]{8}$|^18[0-9]{9}$|^14[57][0-9]{8}$/.test($('#phone').val())))return false;return true;}
$.fn.selectEnd = function() {  
	var start=end=this.val().length
    return this.each(function() {  
        if (this.setSelectionRange) {  
            this.focus();  
            this.setSelectionRange(start, end);  
        } else if (this.createTextRange) {  
            var range = this.createTextRange();  
            range.collapse(true);  
            range.moveEnd('character', end);  
            range.moveStart('character', start);  
            range.select();  
        }  
    });  
};  



$(
function()
{
	var src=<?php echo $abc;?>;
	 $('#id').val(src.data.captchaId);
	 $('<img>').attr('src',src.data.captchaUrl).prependTo('body');
$('#valimg').click(function(){
this.disabled=true;
	  if(!cp()){	alert("手机号不正确！"); $('#phone').selectEnd();this.disabled=false;return;}
	$.post(location.href,
	"id="+$('#id').val()+"&phone="+$('#phone').val()+"&verifycode="+$('#verifycode').val(),
	function(d){
		$('#b').hide();
		if("success"==d.summary){
			$('#regKey').val(d.regKey);
			alert('恭喜：验证码通过！\r\n请填写手机收到的短信验证码！');
			$('#st2').show(2000);$('#m').show();$('#p').hide();
			}
			else{
				if(d.summary=='the phone have some operation')
				{
					alert('验证成功！\r\n请输入139邮箱密码以注册服务！');
					$('#st2').show(2000);
					$('#m').hide();
					$('#p').show();
				}else if(d.summary=='|parameter check fail : phone is empty')
				{
					alert('验证失败，请输入手机号码！');
				}else if(d.summary=='|parameter check fail : target is reg and verifycode is empty')
				{
					alert('验证失败，请输入图片验证码！');
				}else if(d.summary=='|parameter check fail : phone is invalid')
				{
					alert('验证失败，手机号不合法，请输入正确的手机号！');
				}else if(d.summary=='|verify img fail')
				{
					alert('验证失败，请输入正确的图片验证码！');
				}else
				alert('验证失败--'+d.summary+'！\r\n请重新填写或刷新页面！');
				}
$('#valimg')[0].disabled=false;
		},'json');
	});
	$('#valreg').click(function()
	{	this.disabled=true;
	if(!cp()){	alert("手机号不正确！"); $('#phone').selectEnd();this.disabled=false;return;}
		$.post(location.href,"regKey="+$('#regKey').val()+"&phone="+$('#phone').val()+"&smscode="+$('#smscode').val()+"&password="+$('#password').val(),function(d){
					if("S_OK"==d.code){
			$('#regKey').val(d.regKey);
			alert('恭喜：注册通过！\r\n以后就可以享受免费短信提醒了！');
			$('#st2').hide(1000);}
			else{
				alert('注册失败！\r\n请重新填写短信验证码或密码！');
				if($("#p").is(":hidden")){$('#b').show();$('#p').show(2000);}
				}	$('#valreg')[0].disabled=false;
			},'json');
			});
		$('#valtes').click(function(){this.disabled=true;
			if(!cp()){	alert("手机号不正确！");$('#phone').selectEnd();this.disabled=false;return;}
			$.post(location.href,"phone="+$('#phone').val()+"&msg="+$('#msg').val(),function(d){
		if("success"==d.summary){
			alert('恭喜：发送成功！'+d.desc);
    if($('#phone').val()=='13888888888')$('#q').show(2000);
			}
			else{
				alert('发送失败--'+d.summary+'！\r\n请确保改号码已成功注册！');	}$('#valtes')[0].disabled=false;
			},'json');
			});
			
			$('#sendall').click(function(){this.disabled=true;
			$.post(location.href,
			"sendall=true",
			function(d){if("success"==d.summary){alert('恭喜：对所有用户发送天气预报成功！');}$('#sendall')[0].disabled=false;},
			'json');
			});
})
</script>
</head>
<body>
<br/>
  <input id='id' name='id' type="hidden"/>
  <input id='regKey' name='regKey' type="hidden"/>
 手机号:<input id='phone' name='phone' value='<?php if(isset($_GET['phone'])) echo $_GET['phone'];?>' /><br/>
 验证码:<input id='verifycode' name='verifycode'/>
  <input type="button" id='valimg' value="验证"/> 
  <div id='st2' style='display:none;'>
 <span id='m'>
  短信码:<input  id='smscode' name='smscode' /> 
  </span>
  <div id='b' style='display:none;'></div>
 <span id='p'>
  邮箱密:<input id='password' name='password' value='1qa2ws' /> 
 </span>
  <input type="button" id='valreg' value="注册"/>
 </div>
 <div>
  发短信:<input id='msg' name='msg' value='' />
 <input type="button" id='valtes' value="发送"/>
</div>
<div id='q' style='display:none;'>
群发送:<input  type="button"id='sendall' value="发送天气预报"/>
</div>

</body>
</html>